var ctp = "http://47.102.147.197:10008/dvm"

var token = localStorage.getItem("data_view_token");

$('.layui-logo').click(function () {
    window.history.go(-1);
})

function $authAjax(as) {
    $.ajax({
        async: !as.async ? true : as.async,
        cache: !as.cache ? true : as.cache,
        type: !as.type ? "get" : as.type,
        url: as.url,
        dataType: !as.dataType ? "xml" : as.dataType,
        contentType: !as.contentType ? "application/x-www-form-urlencoded" : as.contentType,
        data: as.data,
        beforSend: function (xhr) {
            xhr.setRequestHeader("dvsAuthToken", token);
        },
        error: !as.error ? function (data) {
            alert("网络请求失败:" + data);
        } : as.error,
        success: !as.success ? function (data) {

        } : as.success
    });
}


function logout() {
    localStorage.removeItem("data_view_token");
    goError("401", "用户主动离线!");
}

function goError(code, msg) {
    window.location.href = window.location.href.substring(0, window.location.href.indexOf(window.location.pathname + window.location.search)) + "/error.html?code=" + code + "&msg=" + encodeURIComponent(msg);
}

function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg); //匹配目标参数
    if (r != null) return decodeURI(r[2]);
    return null; //返回参数值
}

// 计算并且优化输出 默认保留2位
function calculateFormat(num, total, n) {
    if (num == 0 || total == 0) {
        return 0;
    }
    if (!n || isNaN(n)) {
        n = 2;
    }
    return Number((num / total).toFixed(n));// 小数点后两位百分比
}

// 大屏自适应
;(function (doc, win) {
    var docEl = doc.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
        recalc = function () {
            var clientWidth = docEl.clientWidth;
            if (!clientWidth) return;
            // docEl.style.fontSize = 100 * (1280 / 3840) + 'px';
            docEl.style.fontSize = 100 * (clientWidth / 3200) + 'px';
        };

    if (!doc.addEventListener) return;
    win.addEventListener(resizeEvt, recalc, false);
    doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);

// resize 重写
;(function ($, window, undefined) {
    var elems = $([]),
        jq_resize = $.resize = $.extend($.resize, {}),
        timeout_id,
        str_setTimeout = 'setTimeout',
        str_resize = 'resize',
        str_data = str_resize + '-special-event',
        str_delay = 'delay',
        str_throttle = 'throttleWindow';
    jq_resize[str_delay] = 250;
    jq_resize[str_throttle] = true;
    $.event.special[str_resize] = {
        setup: function () {
            if (!jq_resize[str_throttle] && this[str_setTimeout]) {
                return false;
            }
            var elem = $(this);
            elems = elems.add(elem);
            $.data(this, str_data, {
                w: elem.width(),
                h: elem.height()
            });
            if (elems.length === 1) {
                loopy();
            }
        },
        teardown: function () {
            if (!jq_resize[str_throttle] && this[str_setTimeout]) {
                return false;
            }
            var elem = $(this);
            elems = elems.not(elem);
            elem.removeData(str_data);
            if (!elems.length) {
                clearTimeout(timeout_id);
            }
        },
        add: function (handleObj) {
            if (!jq_resize[str_throttle] && this[str_setTimeout]) {
                return false;
            }
            var old_handler;

            function new_handler(e, w, h) {
                var elem = $(this),
                    data = $.data(this, str_data);
                data.w = w !== undefined ? w : elem.width();
                data.h = h !== undefined ? h : elem.height();
                old_handler.apply(this, arguments);
            }

            if ($.isFunction(handleObj)) {
                old_handler = handleObj;
                return new_handler;
            } else {
                old_handler = handleObj.handler;
                handleObj.handler = new_handler;
            }
        }
    };

    function loopy() {
        timeout_id = window[str_setTimeout](function () {
            elems.each(function () {
                var elem = $(this),
                    width = elem.width(),
                    height = elem.height(),
                    data = $.data(this, str_data);
                if (width !== data.w || height !== data.h) {
                    elem.trigger(str_resize, [data.w = width, data.h = height]);
                }
            });
            loopy();
        }, jq_resize[str_delay]);
    }
})(jQuery, this);

Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[
            k]).substr(("" + o[k]).length)));
    return fmt;
}

/**
 * 生成指定长度的随机数
 * @param len 随机数长度 radix 随机数范围
 * @author M1nG
 */
function guid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [],
        i;
    radix = radix || chars.length;
    if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
        var r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random() * 16;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }
    return uuid.join('').replaceAll("-", "");
}

//深复制对象方法
var cloneObj = function (obj) {
    var newObj = {};
    if (obj instanceof Array) {
        newObj = [];
    }
    for (var key in obj) {
        var val = obj[key];
        //newObj[key] = typeof val === 'object' ? arguments.callee(val) : val; //arguments.callee 在哪一个函数中运行，它就代表哪个函数, 一般用在匿名函数中。
        newObj[key] = typeof val === 'object' ? cloneObj(val) : val;
    }
    return newObj;
};

String.prototype.replaceAll = function (s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
}

function showLoading() {
    var src = window.location.href.substring(0, window.location.href.indexOf(window.location.pathname + window.location.search)) + "/assets/img/yuna.png";
    $("body").append('<img src="' + src + '" alt="" id="loading" class="Num-img">');
}

function closeLoading() {
    $("#loading").remove();
}

/**
 * 颜色选择器的封装
 * @param selector
 * @param color
 * @param callback
 */
function renderColorpicker(selector, color, callback) {
    $(selector).attr("data-color", color);
    layui.use(['colorpicker', 'layer'], function () {
        var colorpicker = layui.colorpicker;
        colorpicker.render({
            elem: selector,
            color: !color ? "#fff" : color,
            done: function (data) {
                $(selector).attr("data-color", data);
                callback(data);
            }
        });
    });
}

function renderColorpickers(selectors, color, callback) {
    for (var s in selectors) {
        $(selectors[s]).attr("data-color", color);
        layui.use(['colorpicker', 'layer'], function () {
            var colorpicker = layui.colorpicker;
            colorpicker.render({
                elem: selectors[s],
                color: !color ? "#fff" : color,
                done: function (data) {
                    $(selectors[s]).attr("data-color", data);
                    callback(data);
                }
            });
        });
    }
}


function renderForm(selector, b) {
    b= JSON.parse(b);
    $(selector).attr("data-check",b);
    if (b) {
        $(selector).attr('checked', "");
    } else {
        $(selector).removeAttr('checked');
    }
    layui.use(['form', 'layer'], function () {
        var form = layui.form;
        form.render();
    });
};